import Vue from 'vue'
import Vuex from 'vuex'
import $api from "../config/api";
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		token: uni.getStorageSync('token') || '',
		userInfo: uni.getStorageSync('userInfo') || {
			id: 1,
			points: 1000
		},
		balance: 0
	},
	getters: {
		userInfo: state => state.userInfo,
		token: state => state.token,
		balance: state => state.balance
	},
	mutations: {
		SET_USERINFO(state, userInfo) {
			uni.setStorageSync('userInfo', userInfo)
			state.token = userInfo
		},
		SET_TOKEN(state, token) {
			uni.setStorageSync('token', token)
			state.token = token
		},
		SET_BALANCE(state, balance) {
			state.balance = balance
		},
		logout(state) {
			state.userInfo = {}
			state.token = ''
			state.balance = 0
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('token')
		}
	},
	actions: {
		getUserInfo({ commit, state }) {
			if (state.token) {
				uni.showLoading()
				$api.getMemberInfo().then(res => {
					if (res) {
						commit('SET_USERINFO', res)
					} else {
						commit('logout')
						// 重载小程序
					}
					uni.hideLoading()
				}).catch(() => {
					commit('logout')
				})
			} else {
				commit('logout')
			}
		},
		// 获取余额
		getBalance({ commit, state }) {
			if (state.token) {
				uni.showLoading()
				$api.getBalance().then(res => {
					commit('SET_BALANCE', res.amount)
					uni.hideLoading()
				}).catch(() => {
					// commit('logout')
				})
			} else {
				commit('logout')
			}
		},
	}
})

export default store
